<template>
  <div class="game-user">
    <div class="back-box">
      <span @click="backPageHandle" class="back-btn"><i class="el-icon-back"></i>返回</span>
      <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
      <span>游戏用户管理</span>
    </div>
    <transition name="el-zoom-in-top">
      <el-form v-show="searchFormVisible" inline size="mini" :model="searchForm" ref="searchForm" @keyup.enter.native="searchHandle">
        <el-form-item prop="word" label="游戏用户检索">
          <el-input v-model="searchForm.word" clearable placeholder="请输入游戏用户名称"></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select v-model="searchForm.status" clearable placeholder="请选择状态">
            <el-option v-for="statusEnum in statusEnumList" :key="'status' + statusEnum.value"
                       :label="statusEnum.name" :value="statusEnum.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchHandle" type="primary" icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetFormHandle" plain icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>
    <div class="g-u-tool">
      <el-button :disabled="dataLoad" @click="$refs.gameUserDialog.initDialog(undefined, searchForm.gameId)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
      <el-button :disabled="gameUserSelection.length === 0 || dataLoad || buttonLoad" @click="updateGameUserStatusHandle(undefined, 0)"
                 type="success" size="mini" plain icon="el-icon-circle-plus-outline">启用</el-button>
      <el-button :disabled="gameUserSelection.length === 0 || dataLoad || buttonLoad" @click="updateGameUserStatusHandle(undefined, 1)"
                 type="warning" size="mini" plain icon="el-icon-circle-close">禁用</el-button>
      <el-button :disabled="gameUserSelection.length === 0 || dataLoad || buttonLoad" @click="deleteGameUserHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <right-tool-bar :search-visible="searchFormVisible" :search-load="dataLoad"
                      @toggle-search="searchFormVisible = !searchFormVisible" @refresh-table="getGameUserList" />
    </div>
    <el-table
      v-loading="dataLoad"
      element-loading-text="游戏用户数据加载中..."
      element-loading-spinner="el-icon-loading"
      :data="gameUserList"
      @sort-change="sortChangeHandle"
      @selection-change="(val) => this.gameUserSelection = val"
      ref="gameUserTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="username" header-align="center" align="center" label="用户名称"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="gameTotalNum" header-align="center" align="center" label="可用次数"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="gameUseNum" header-align="center" align="center" label="已用次数"></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="{row}">
          <el-tag :type="row.status === 0 ? 'primary' : 'danger'">
            {{ row.status | baseFormat(statusEnumList) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注"></el-table-column>
      <el-table-column sortable="custom" :sort-orders="sortOrders" prop="createTime" header-align="center" align="center" label="创建时间" width="135"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        header-align="left"
        width="160"
        label="操作">
        <template v-slot="{ row }">
          <div>
            <el-button :disabled="row.status === 1" type="text" icon="el-icon-edit" @click="$refs.gameUserDialog.initDialog(row, undefined)">
              增加次数
            </el-button>
            <el-button type="text" icon="el-icon-view" @click="$refs.gameUserFlowDialog.initDialog(row.id, 1)">
              流水
            </el-button>
          </div>
          <div>
            <el-button v-if="row.status === 1" type="text" icon="el-icon-check" @click="updateGameUserStatusHandle(row, 0)">
              启用
            </el-button>
            <el-button v-if="row.status === 0" type="text" icon="el-icon-close" @click="updateGameUserStatusHandle(row, 1)">
              禁用
            </el-button>
            <el-button type="text" icon="el-icon-delete" @click="deleteGameUserHandle(row)" class="danger-color">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 游戏用户添加/修改弹出框 -->
    <game-user-dialog ref="gameUserDialog" @refresh-table="getGameUserList" />

    <!-- 游戏用户流水查看弹出框 -->
    <game-user-flow-dialog ref="gameUserFlowDialog" />
  </div>
</template>

<script>
  import RightToolBar from "@/components/common/right-toolbar";
  import GameUserDialog from "@/components/game/user/save-update";
  import GameUserFlowDialog from "@/components/game/flow";
  export default {
    layout: 'admin',
    components: {
      RightToolBar, GameUserDialog, GameUserFlowDialog,
    },
    data() {
      return {
        // 游戏用户列表
        gameUserList: [],
        // 选中的游戏用户数据
        gameUserSelection: [],
        // 游戏用户总数
        totalNum: 0,
        // 状态枚举列表
        statusEnumList: [
          {
            name: '可用',
            value: 0
          },
          {
            name: '不可用',
            value: 1
          }
        ],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 游戏用户管理检索表单显示状态[true-显示 false-隐藏]
        searchFormVisible: true,
        // 游戏用户管理检索表单对象
        searchForm: {
          // 游戏主键
          gameId: undefined,
          // 游戏用户名称
          word: '',
          // 状态
          status: '',
          // 当前展示页码
          page: 1,
          // 当前页显示个数
          limit: 10,
          // 排序字段
          field: 'id',
          // 排序方式
          order: 'descending'
        },
        // 数据加载状态[false-不加载 true-加载]
        dataLoad: false,
        // 按钮禁用状态[true-禁用 false-可用]
        buttonLoad: false,
        // 游戏管理页面检索参数
        prePageSearchForm: '',
      }
    },
    filters: {
      /**
       * 枚举映射方法
       * @param {number} value 参数值
       * @param {Array}  list  枚举列表
       */
      baseFormat(value, list) {
        for (let obj of list) {
          if (obj.value === value) {
            return obj.name;
          }
        }
        return '未知';
      }
    },
    asyncData({ app, params } ) {
      if (!params.gameId) {
        app.router.replace('/admin/game');
        return;
      }
      // console.log('params', params);
      let data = {
        gameId: params.gameId,
        page: 1,
        limit: 10,
        field: 'id',
        order: 'descending'
      }
      return app.$axios.$post('/game-user/page/list', data)
        .then(({ data }) => {
          return {
            gameUserList: data.data,
            totalNum: data.totalNum,
            searchForm: {
              gameId: params.gameId,
              word: '',
              status: '',
              page: 1,
              limit: 10,
              field: 'id',
              order: 'descending'
            },
            prePageSearchForm: params.prePageSearchForm
          }
        })
        .catch(() => {});
    },
    methods: {
      /**
       * 回退到游戏管理页面
       */
      backPageHandle() {
        this.$router.replace({name: 'admin-game', params: { searchForm: this.prePageSearchForm }});
      },
      /**
       * 查询游戏用户事件
       */
      searchHandle() {
        this.searchForm.page = 1;

        this.getGameUserList();
      },
      /**
       * 获取游戏用户列表方法
       */
      getGameUserList() {
        // 开始加载
        this.dataLoad = true;
        this.$axios.$post('/game-user/page/list', this.searchForm)
          .then(({ data }) => {
            this.gameUserList = data.data;
            this.totalNum = data.totalNum;
          })
          .catch(() => {})
          .finally(() => {
            // 加载结束
            this.dataLoad = false;
          })
      },
      /**
       * 更新游戏用户状态事件
       * @param gameUser  游戏用户对象
       * @param newStatus 新状态
       */
      updateGameUserStatusHandle(gameUser, newStatus) {
        let data = {
          idList: [],
          status: newStatus
        }
        let message;
        if (gameUser) {
          // 单个
          data.idList.push(gameUser.id);
          message = `您确定要‘${newStatus === 0 ? '启用' : '禁用'}’游戏用户吗，是否继续？`
        } else {
          // 批量
          data.idList = this.gameUserSelection.filter(_gameUser => _gameUser.status !== newStatus).map(_gameUser => _gameUser.id);
          if (data.idList.length === 0) {
            this.notify('', '温馨提示', `您选中的数据无需进行’${newStatus === 0 ? '启用' : '禁用'}‘操作`);
            return
          }
          message = `您确定要批量‘${newStatus === 0 ? '启用' : '禁用'}’游戏用户吗，是否继续？`
        }
        this.$confirm(message, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮禁用
          this.buttonLoad = true;
          return this.$axios.$post('/game-user/update/status', data);
        })
          .then(() => {
            let successMessage;
            if (gameUser) {
              successMessage = `‘${newStatus === 0 ? '启用' : '禁用'}’游戏用户操作成功`;
              // 更新状态
              gameUser.status = newStatus;
            } else {
              successMessage = `批量‘${newStatus === 0 ? '启用' : '禁用'}’游戏用户操作成功`;
              // 更新状态
              this.gameUserSelection.forEach(_gameUser => _gameUser.status = newStatus);
              // 清空表格选中数据
              this.$refs.gameUserTable.clearSelection();
            }
            this.notify('success', '操作成功', successMessage);
          })
          .catch(err => {
            if (err.code === 409) {
              this.getGameUserList();
            }
          })
          .finally(() => {
            // 按钮恢复可使用
            this.buttonLoad = false;
          });
      },
      /**
       * 删除游戏用户事件
       * @param {Object} gameUser 游戏用户对象
       */
      deleteGameUserHandle(gameUser) {
        let data = {
          gameId: this.searchForm.gameId,
          idList: undefined,
          userIdList: undefined,
        }
        let message;
        if (gameUser) {
          // 单个删除
          data.idList = [ gameUser.id ];
          data.userIdList = [ gameUser.userId ];
          message = `您确定要删除‘${gameUser.username}’游戏游戏吗，是否继续？`
        } else {
          // 批量删除
          data.idList = [];
          data.userIdList = [];
          this.gameUserSelection.forEach(_gameUser => {
            data.idList.push(_gameUser.id);
            data.userIdList.push(_gameUser.userId);
          });
          message = '您确定要删除选中的游戏用户吗，是否继续？'
        }
        this.$confirm(message, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }).then(() => {
          // 按钮禁用
          this.buttonLoad = true;
          return this.$axios.$delete('/game-user/delete', { data: data });
        }).then(() => {
          this.notify('success', '操作成功', '游戏用户删除成功');
          // 刷新表格
          this.getGameUserList();
        }).catch(err => {
          if (err.code === 409) {
            this.getGameUserList();
          }
        }).finally(() => {
          // 按钮恢复可使用
          this.buttonLoad = false;
        });
      },
      /**
       * 表格选择字段排序事件
       * @param {string} prop  排序字段
       * @param {string} order 排序方式
       */
      sortChangeHandle( { prop, order } ) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.field = prop;
        searchForm.order = order;

        this.getGameUserList();
      },
      /**
       * 每页显示个数变化事件
       * @param {number} size 最新显示个数值
       */
      sizeChangeHandle(size) {
        let searchForm = this.searchForm;
        searchForm.page = 1;
        searchForm.limit = size;
        this.getGameUserList();
      },
      /**
       * '点击特定页码'、'上一页'、'下一页'操作事件
       * @param {number} index 最新页码
       */
      currentChangeHandle(index) {
        let searchForm = this.searchForm;
        if (searchForm.page === index) {
          return;
        }
        searchForm.page = index;
        this.getGameUserList();
      },
      /**
       * 重置检索表单对象事件
       */
      resetFormHandle() {
        // 重置表单
        this.$refs.searchForm.resetFields();

        this.searchForm.page = 1;
      },
    }
  }
</script>

<style scoped>
  .game-user .back-box {
    font-size: 14px;
    height: 35px;
    line-height: 35px;
    margin-bottom: 7px;
  }
  .game-user .back-box .back-btn {
    height: 100%;
    cursor: pointer
  }
  .game-user .back-box .back-btn:hover {
    background-color: #F2F6FC;
  }
  .game-user .g-u-tool {
    margin-bottom: 10px;
  }
  .game-user .paging {
    float: right;
    margin: 7px;
  }
</style>
